﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AzukiMap.DataSource;
using AzukiMap.Map;
using Geotools.Geometries;
using AzukiMap.Request;
using AzukiMap.Renderer;
using System.Windows.Threading;

namespace AzukiMap.Layer
{
    public class PostGisLayer : VectorLayer
    {
        PostGisTable _pgTable;
        PostGisDataRequest _pgRequest;
        PostGisDataParser _pgParser;

        public PostGisLayer(PostGisTable pgTable, MapCanvas mapCanvas, string name, GTPolygon extent)
            : base((VectorSource)pgTable, mapCanvas, name, extent)
        {
            init(pgTable);
        }

        public PostGisLayer(PostGisTable pgTable, MapCanvas mapCanvas, string name)
            : base((VectorSource)pgTable, mapCanvas, name)
        {
            init(pgTable);
        }

        void init(PostGisTable pgTable)
        {
            _pgTable = pgTable;
            _pgRequest = new PostGisDataRequest(MapCanvas, this);
            _pgRequest.GetDataCompleted += new GetDataCompletedHandler(_pgRequest_GetDataCompleted);
        }

        public override void Draw()
        {
            if (!CheckScale())
            {
                return;
            }
            IsDrawing = true;
            _pgRequest.Request();
        }

        void _pgRequest_GetDataCompleted(object sender, GetDataCompletedArgs e)
        {
            _pgParser = new PostGisDataParser(e.DataStream);
            int numOfGeom = _pgParser.NumOfObjects;

            // TODO: get uniq ID from records.
            int id = 0;
            IVectorStyle vStyle;
            foreach (PostGisRecord record in _pgParser)
            {
                // No layer theme
                if (record.ThemeId == -1)
                {
                    vStyle = _defaultStyle;
                }
                else
                {
                    vStyle = _layerThemes[record.ThemeId].Style;
                }
                _renderer.DrawGeometry(id, record.Geometry, vStyle);
            }
        }

    }
}
